const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const a = options => {
  console.log(123)
}

// 域名
const baseUrl = "https://www.tuisitang.cn"
// 缓存键 & header键
const zxAccessTokenStorageKeyName = "Zx-Access-Token"

/**
 * request封装，根据约定封装，方便调用
 * 支持参数配置
 * {
 *     loading: true, // 请求过程是否开启loading
 *     loadingHide: "delay" // 请求过程结束后，如何隐藏loading，delay延迟隐藏，imidiate立即隐藏
 *     loadingText: "请求中..." // loading的文案
 * }
 */
const request = (uri, reqData, callback, requestOptions) => {
  let options = handleRequestOptions(requestOptions);
  let logData = {
    uri: uri,
    reqData: reqData,
    requestOptions: options
  };

  // 请求是否开启loading
  if (options['loading']) {
    wx.showLoading({
      title: options['loadingText'],
    })
  }
  // 正式请求
  return wx.request({
    url: baseUrl + (uri || ""),
    header: {
      "Charset": "UTF-8",
      "Content-Type": "application/json",
      // 'Zx-Access-Token': getZxAccessToken(),
      "Zx-Open-Id": getZxOpenId()
    },
    data: reqData,
    dataType: "json",
    method: "POST",
    // 请求成功
    success: function(res) {
      logData["resData"] = res.data;
      if (res.statusCode == 401) {
        // 跳转到首页
        return wx.redirectTo({
          url: '/pages/login/index',
        });
      }

      // 处理回调函数
      if (typeof callback === "function") {
        return callback(res)
        if (res.data.errCode == 0) {
          return callback(res)
        } else {
          return toast(res.data.errMsg);
        }
      }
      console.log("未设置成功回调函数")
    },
    // 处理系统异常
    fail: function(res) {
      console.log("接口调用异常")
    },
    // 清理资源
    complete: function(res) {
      if (options['loadingHide'] == "imidiate") {
        wx.hideLoading()
      } else {
        setTimeout(function() {
          wx.hideLoading()
        }, 150);
      }
    }
  })
}

/**
 * 记录日志
 */
const log = data => {
  let logs = wx.getStorageSync("requestLogs") || {};
  let logIndex = wx.getStorageSync("requestLogIndex") || [];

  let dateObj = new Date();
  let index = {
    index: dateObj.getTime(),
    show: formatTime(dateObj) + " > " + data.uri
  };

  logIndex.push(index);
  logs[index.index] = {
    uri: data.uri,
    detail: JSON.stringify(data)
  };

  wx.setStorage({
    key: 'requestLogs',
    data: logs,
  });

  wx.setStorage({
    key: 'requestLogIndex',
    data: logIndex,
  });
}

/**
 * 处理loading配置参数
 */
const handleRequestOptions = (requestOptions) => {
  let options = requestOptions;
  // 如果不给配置参数，使用默认配置参数
  if (options === undefined) {
    options = {
      "loading": true,
      "loadingHide": "delay",
      "loadingText": "请求中..."
    };
  } else {
    // 如果loading未设置，使用ture作为默认值
    if (options["loading"] === undefined) {
      options["loading"] = true;
    }
    // 如果loading后的隐藏loading没有设置，默认imidiate，否则使用延迟隐藏
    if (options["loadingHide"] === undefined) {
      options["loadingHide"] = "delay";
    }

    // 如果loading后的隐藏loading没有设置，默认imidiate，否则使用延迟隐藏
    if (options["loadingText"] === undefined) {
      options["loadingText"] = "请求中...";
    }
  }
  return options;
}

// 上传
const upload = (name, uri, filePath, formData, callback) => {
  wx.uploadFile({
    url: baseUrl + (uri || ""),
    filePath: filePath,
    name: name,
    formData: formData,
    dataType: "json",
    header: {
      "Zx-Open-Id": getZxOpenId()
    },
    success: function (res) {
      if (typeof callback === "function") {
        return callback(res)
      }
    }
  })
}

/**
 * 文件上传
 */
const uploadFile = (uri, filePath, formData, callback) => {
  upload("file", uri, filePath, formData, callback);
}

/**
 * 图片上传
 */
const uploadImg = (uri, filePath, formData, callback) => {
  upload("images", uri, filePath, formData, callback);
}

/**
 * 获取登陆token
 */
const getZxAccessToken = () => {
  let zxAccessToken = wx.getStorageSync(zxAccessTokenStorageKeyName)
  if (typeof zxAccessToken === 'string')
    return zxAccessToken
  else
    return ""
}

/**
 * 设置登陆token
 */
const setZxAccessToken = token => {
  wx.setStorage({
    key: zxAccessTokenStorageKeyName,
    data: token,
    success: function() {
      // console.log('设置token缓存成功', zxAccessTokenStorageKeyName, token)
    }
  })
}

/**
 * 从后台获取openId
 */
const getZxOpenId = () => {
  let openId = wx.getStorageSync("openId");
  if (!openId) {
    openId = "";
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: baseUrl + '/api/getOpenid',
          method: "POST",
          header: {
            "Charset": "UTF-8",
            "Content-Type": "application/json",
            "Zx-Code": res.code
          },
          success: res => {
            if (res.data.errCode == '0') {
              openId = res.data.data;
            }
            wx.setStorage({
              key: "openId",
              data: openId,
            });
          }
        });
      }
    })
  }
  return openId;
}

/**
 * loading
 * 
 * 支持参数 title loading的title
 */
const loading = title => {
  wx.showLoading({
    title: title,
    mask: true,
  })
}

/**
 * toast 支持 title, icon, duration设置
 */
const toast = (title, icon, duration) => {
  wx.showToast({
    title: title,
    icon: icon || "none",
    duration: duration || 1500,
    mask: true
  })
}

// 克隆方法
const clone = (obj) => {
  var o;
  if (typeof obj == "object") {
    if (obj === null) {
      o = null;
    } else {
      if (obj instanceof Array) {
        o = [];
        for (var i = 0, len = obj.length; i < len; i++) {
          o.push(clone(obj[i]));
        }
      } else {
        o = {};
        for (var j in obj) {
          o[j] = clone(obj[j]);
        }
      }
    }
  } else {
    o = obj;
  }
  return o;
}

// 导出公共方法
module.exports = {
  formatTime: formatTime,
  request: request,
  uploadFile: uploadFile,
  uploadImg: uploadImg,
  setZxAccessToken: setZxAccessToken,
  getZxAccessToken: getZxAccessToken,
  loading: loading,
  toast: toast,
  getZxOpenId: getZxOpenId,
  baseUrl: baseUrl,
  clone: clone,
}